package org.ricks.common.conf;

import org.ricks.utils.FileUtil;
import org.ricks.utils.NodeUtils;
import org.ricks.utils.ObjectUtil;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author chenwei
 * @Title:
 * @Package
 * @Description:
 * @date 2020/8/717:16
 */
public abstract class AbstractConfLoader {


    public abstract void loadResult() throws Exception;

    public abstract Map<String, Object> getSource();

    protected void loadSource(Map<org.ricks.common.conf.LoadFileName, Object> map, List<org.ricks.common.conf.LoadFileName> loadFileNameList) throws Exception {
        for (org.ricks.common.conf.LoadFileName loadFileName : loadFileNameList) {
            File file = FileUtil.getFile(loadFileName.getFileName());
            if(!file.exists()) continue;
            InputStream inputStream = new FileInputStream(file);
            Object sourceResult = loadFileName.getLoadSource().loadSources(inputStream);
            map.putIfAbsent(loadFileName, sourceResult);
        }
    }

    @SuppressWarnings("unchecked")
    protected Map<String, Object> mergeSource(Map<LoadFileName, Object> map) {
        Map<String, Object> res = new HashMap<>();
        map.forEach((loadFileName, content) -> {
            if(!Objects.isNull(content)) {
                Map<String, Object> soureResult = (Map<String, Object>) ObjectUtil.deepCopy(content);
                NodeUtils.merge(res, soureResult, false);
            }
        });
        return res;
    }
}

